<?php

namespace app\api\model;

use think\Db;
use think\Model;

class User extends Model
{
    private static $instance = null;

    public function __construct($data = [])
    {
        parent::__construct($data);
    }

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            $obj = new static();
            self::$instance = $obj;
            return $obj;
        } else {
            return self::$instance;
        }
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo($where = [])
    {
        $info = Db::name('user')->where($where)->field('id AS uid, user_name, nick_name, phone, openid, sex, paper_num, token,status,pid')->find();
        return $info;
    }

    /**
     * 插入用户信息
     */
    public function addUserInfo($addData = [])
    {
        $res = Db::name('user')->insert($addData);
        return $res;
    }

    /**
     * 更新用户信息
     */
    public function updateUserInfo($where = [], $upData = [])
    {
        $res = Db::name('user')->where($where)->update($upData);
        return $res;
    }

    /**
     * 变更企业认证状态
     */
    public function updateUserContact($params, $isCertified = 2)
    {
        $data = [
            'uid' => $params['uid'],
            'com_name' => $params['name'],
            'contact_name' => $params['contactsName'],
            'contact_tel' => $params['contactsMobile'],
            'email' => $params['contactsEmail'],
            'credit_code' => str_replace(' ', '', $params['regCode']),
            'type' => $params['type'],
            'legal_name' => $params['legalPerson'],
            'legal_card_no' => $params['legalPersonIdentity'],
            'legal_tel' => $params['mobile'],
            'taxpayer_name' => $params['legalPerson'],
            'taxpayer_id' => $params['regCode'],
            'invoice_company_name' => $params['name'],
            'is_certified' => $isCertified,
            'signer' => $params['contactsName'],
            'signerContact' => $params['contactsMobile'],
            'created_at' => datetime(time(), 'Y-m-d H:i:s'),
            'authorization' => isset($params['authorization']) ? $params['authorization'] : ''
        ];

        if (isset($params['businessLicense']))
        {
            $data['com_images'] = json_encode([$params['businessLicense']]);
            $data['business_license'] = json_encode([$params['businessLicense']]);
        }
        if (isset($params['idCard']))
        {
            $data['legal_id_card'] = $params['idCard'];
        }
        if (isset($params['legalPersonName']))
        {
            $data['legal_person_name'] = $params['legalPersonName'];
        }

        $userContact = Db::name('user_contact')->where([
            'uid' => ['eq', $params['uid']],
            'credit_code' => ['eq', $params['regCode']]
        ])->find();
        if ($userContact)
        {
            $data['updated_at'] = datetime(time(), 'Y-m-d H:i:s');
            Db::name('user_contact')->where([
                'uid' => ['eq', $params['uid']],
                'credit_code' => ['eq', $params['regCode']]
            ])->update($data);
        }else{
            $data['created_at'] = datetime(time(), 'Y-m-d H:i:s');
            Db::name('user_contact')->insert($data);
        }

        $saveData = [
            'is_certified' => $isCertified,
        ];

        if (isset($params['taskId']))
        {
            $saveData['task_id'] = $params['taskId'];
        }

        Db::name('user_contact')->where([
            'credit_code' => ['eq', $params['regCode']],
            'uid' => ['eq', $params['uid']]
        ])->update($saveData);
        return true;
    }

    /**
     * 获取企业信息
     */
    public function getContactInfo($where = [])
    {
        $contactInfo = Db::name('user_contact')->where($where)->find();

        $businessLicense = json_decode($contactInfo['business_license'], true);

        $desc = Db::name('actions_record')->where([
            'target_id' => ['eq', $contactInfo['id']]
        ])->order('id DESC')->value('remark');

        $uName = Db::name('admin')->where([
            'id' => ['eq', $contactInfo['uid']]
        ])->value('username');

        return [
            'id' => $contactInfo['id'],
            'uid' => $contactInfo['uid'],
            'uName' => $uName,
            'name' => $contactInfo['com_name'],
            'mobile' => $contactInfo['legal_tel'],
            'regCode' => $contactInfo['credit_code'],
            'legalPerson' => $contactInfo['legal_name'],
            'legalPersonIdentity' => $contactInfo['legal_card_no'],
            'contactsMobile' => $contactInfo['signerContact'],
            'contactsName' => $contactInfo['signer'],
            'contactsEmail' => $contactInfo['email'],
            'type' => $contactInfo['type'],
            'authorization' => $contactInfo['authorization'],
            'businessLicense' => isset($businessLicense[0]) ? $businessLicense[0] : '',
            'idCard' => $contactInfo['legal_id_card'],
            'legalPersonName' => $contactInfo['legal_person_name'],
            'desc' => empty($desc) ? '' : $desc
        ];
    }

    /**
     * 获取、更新系统操作日志
     */
    public function actionsRecordLog($targetId, $adminId, $type = 5, $action = '', $remark = '', $isSave = 0)
    {
        if ($isSave)
        {
            $saveData = [
                'target_id' => $targetId,
                'admin_id' => $adminId,
                'type' => $type,
                'action' => $action,
                'remark' => $remark,
                'created_at' => datetime(time(), 'Y-m-d H:i:s')
            ];
            return Db::name('actions_record')->insert($saveData);
        }else{
            $list = Db::name('actions_record')->alias('ar')
                ->join('t_admin a', 'ar.admin_id = a.id', 'left')
                ->where([
                'ar.target_id' => ['eq', $targetId],
                'ar.type' => ['eq', $type]
            ])->field('ar.target_id,a.username,ar.type,ar.action,ar.remark,ar.created_at')->select();
            return $list;
        }
    }

}